<template>
    <div class="sensor">
        <div class="header">
            <div class="title">
                <div class="title-box" :style="{ background: data.color }">
                    <i class="iconfont icon-chuanganqizhuangtai"></i>
                </div>
                <div>{{ data.type + "：" + data.name }}</div>
                <div v-if="data.pattern === 3" style="padding-left: 15px">
                    <text class="histor-title">历史趋势</text>
                    <text
                        class="histor-text"
                        :class="[
                            historicalTrend >= 0 && historicalTrend <= 33 && 'one',
                            historicalTrend <= 66 && historicalTrend > 33 && 'two',
                            historicalTrend > 66 && historicalTrend <= 100 && 'three'
                        ]"
                        >{{ historicalTrend }}%</text
                    >
                </div>
                <div v-else-if="data.pattern === 2" style="padding-left: 15px">
                    <text :class="{ change: changeNumber == 1 }" class="nochange" style="cursor: pointer" @click="changes(1)">时域图</text>
                    ·
                    <text :class="{ change: changeNumber == 2 }" class="nochange" style="cursor: pointer" @click="changes(2)">频域图</text>
                </div>
            </div>
            <div class="select" v-if="data.pattern !== 1">
                <div class="select-label">展示对象</div>
                <el-select v-model="selectValue" placeholder="请选择展示对象" :suffix-icon="CaretBottom" @change="change">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
        </div>
        <div class="article">
            <div class="article-wrapper" :style="{ width: !data.isStrain ? '520px' : '100%' }">
                <div style="display: flex">
                    <div class="item top" ref="topRef"></div>
                    <div class="table-main" style="font-size: 14px; align-self: flex-end; height: 184px" v-if="data.pattern === 1">
                        <table>
                            <thead>
                                <tr>
                                    <th>描述对象</th>
                                    <th>历史趋势(%)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="item in tableData">
                                    <td>{{ item.name }}</td>
                                    <td :class="[item.value >= 0 && item.value <= 33 && 'one', item.value <= 66 && item.value > 33 && 'two', item.value > 66 && item.value <= 100 && 'three']">
                                        {{ item.value }}
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div style="position: relative">
                    <div class="item" ref="bottomRef"></div>
                    <div v-if="data.isStrain" class="choose" style="font-size: 14px; left: 80px; top: 3px">
                        <div :class="{ time: time == 1 }" @click="changeTime(1)">年度</div>
                        <div class="point"></div>
                        <div :class="{ time: time == 3 }" @click="changeTime(3)">季度</div>
                        <div class="point"></div>
                        <div :class="{ time: time == 2 }" @click="changeTime(2)">月度</div>
                    </div>
                </div>
            </div>
            <div v-if="!data.isStrain">
                <div class="table-main" style="font-size: 14px">
                    <table>
                        <thead>
                            <tr>
                                <th>振动特征</th>
                                <th>数值</th>
                                <th>趋势平稳度</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="item in tableData">
                                <td>{{ item.evaluateObject }}</td>
                                <td>{{ item.sensorValue }}</td>
                                <td
                                    :class="[
                                        item.tendencyChart >= 0 && item.tendencyChart <= 33 && 'one',
                                        item.tendencyChart <= 66 && item.tendencyChart > 33 && 'two',
                                        item.tendencyChart > 66 && item.tendencyChart <= 100 && 'three'
                                    ]"
                                >
                                    {{ item.tendencyChart }}%
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="table-main" style="font-size: 14px; margin-top: 20px">
                    <table>
                        <thead>
                            <tr>
                                <th>主要振动源</th>
                                <th>推测原因</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="item in tableDatas">
                                <td>{{ item.vibrationSource }}</td>
                                <td>{{ item.vibrationCause }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="close" @click="close">x</div>
    </div>
</template>

<script setup>
import { CaretBottom } from "@element-plus/icons-vue";
import { getNowDataOption, getTrendOptions } from "../config.js";
import { nextTick, ref } from "vue";
import { useInterVal } from "@/hooks/useInterVal.js";
import echarts from "@/echarts";
import {
    getstrainsensorenumasync,
    getstrainsensortendency,
    getstatisticsshocksensorbylocation,
    getshocksensor,
    getshocksensormechanismvibration,
    getstrainsensortendencybynow,
    getStrainSensorByDateNow,
    getTiltTrendstabilityHistory
} from "@/service/api/faultDetection.js";

const props = defineProps({
    formData: {
        type: Object,
        required: true
    }
});
const { setsInterVal, clearsInterval } = useInterVal();
const emits = defineEmits(["close", "getdata"]);
const changeNumber = ref(1);
const historicalTrend = ref("");
const time = ref(1);
const selectValue = ref();
const options = ref([]);
const tableData = ref([]);
const tableDatas = ref([]);
const topRef = ref(null);
const bottomRef = ref(null);
const data = ref({});

//传感器实时数据
function getstrainsensorbydatenowFn(opt) {
    let req = {};
    if (data.value.isStrain) {
        req = {
            equipmentCode: props.formData.equipmentCode,
            code: data.value.pointCodes,
            strainSensorObj: selectValue.value,
            sensorType: data.value.pattern,
            parentCode: data.value.code
        };
    } else {
        req = { equipmentCode: props.formData.equipmentCode, code: data.value.pointCodes[selectValue.value].pointCodes, sensorType: data.value.pattern, parentCode: data.value.code };
    }
    setsInterVal(() => {
        getStrainSensorByDateNow(req).then((res) => {
            if (res.code === 200) {
                const option = getNowDataOption({
                    titleName: opt.titleName[0],
                    xAxisData: res?.data[0]?.dateTimeName || [],
                    yAxisName: opt.yAxisName,
                    xAxisName: changeNumber.value === 2 ? "频率(Hz)" : "",
                    seriesData: data.value.isStrain ? res?.data || [] : [res?.data?.find((item) => item.location === "1").speed || []]
                });
                if (!data.value.isStrain) {
                    option.tooltip = {
                        show: true,
                        trigger: "axis"
                    };
                }
                echarts.getInstanceByDom(topRef.value).setOption(option);
                if (!data.value.isStrain) {
                    const option1 = getNowDataOption({
                        titleName: opt.titleName[1],
                        xAxisData: res?.data[0]?.dateTimeName || [],
                        yAxisName: opt.yAxisName,
                        seriesData: data.value.isStrain ? res?.data || [] : [res?.data?.find((item) => item.location === "2").speed || []]
                    });
                    option1.tooltip = {
                        show: true,
                        trigger: "axis"
                    };
                    echarts.getInstanceByDom(bottomRef.value).setOption(option1);
                }
            }
        });
    });
}
//传感器频域图
function getshocksensorFn(options) {
    setsInterVal(() => {
        getshocksensor({
            equipmentCode: props.formData.equipmentCode,
            locations: data.value.pointCodes[selectValue.value].pointCodes,
            monitoringObject: data.value.order,
            parentCode: data.value.code
        }).then((res) => {
            const option1 = getNowDataOption({
                titleName: options.titleName[0],
                xAxisData: res?.data[0]?.dateValue || [],
                yAxisName: options.yAxisName,
                xAxisName: changeNumber.value === 2 ? "频率(Hz)" : "",
                seriesData: [res?.data[0]?.healthValue || []]
            });
            option1.tooltip = {
                show: true,
                trigger: "axis"
            };
            echarts.getInstanceByDom(topRef.value).setOption(option1);
            const option2 = getNowDataOption({
                titleName: options.titleName[1],
                xAxisData: res.data[1]?.dateValue || [],
                yAxisName: options.yAxisName,
                xAxisName: changeNumber.value === 2 ? "频率(Hz)" : "",
                seriesData: [res?.data[1]?.healthValue || []]
            });
            option2.tooltip = {
                show: true,
                trigger: "axis"
            };
            echarts.getInstanceByDom(bottomRef.value).setOption(option2);
        });
    });
}
//应变传感器历史数据
function getstrainsensortendencyFn(reqData, options) {
    getstrainsensortendency(reqData).then((res) => {
        if (res.code === 200) {
            const option = getTrendOptions({
                titleName: options.titleName,
                xAxisData: res.data?.dateValue || [],
                yAxisName: options.yAxisName,
                seriesData: [res.data?.tendencyValue || []]
            });
            echarts.getInstanceByDom(bottomRef.value).setOption(option);
        }
    });
}
function getstrainsensortendencybynowFn(reqData) {
    getstrainsensortendencybynow(reqData).then((res) => {
        if (res.code === 200) historicalTrend.value = res.data.tendencyValue;
    });
}
//数据源
const getData = async (dataObj) => {
    console.log(dataObj);
    clearsInterval();
    data.value = dataObj;
    selectValue.value = "";
    changeNumber.value = 1;
    time.value = 1;
    echarts.dispose(topRef.value);
    echarts.dispose(bottomRef.value);
    nextTick(async () => {
        echarts.init(topRef.value);
        echarts.init(bottomRef.value);
        if (data.value.isStrain) {
            const res = await getstrainsensorenumasync();
            if (res.code === 200) {
                options.value = res.data.map((item) => ({ label: item.name, value: item.value }));
            }
            selectValue.value = options.value[0].value;
            getstrainsensorbydatenowFn({
                titleName: ["实时数据"],
                yAxisName: dataObj.pattern === 1 ? "角度（°）" : options.value.find((item) => item.value === selectValue.value).label
            });
            getstrainsensortendencybynowFn({ equipmentCode: props.formData.equipmentCode, parentCode: data.value.code });
            getstrainsensortendencyFn(
                { equipmentCode: props.formData.equipmentCode, statisticsType: time.value, monitorLocation: "主结构", parentCode: data.value.code },
                { titleName: "趋势水平", yAxisName: "趋势水平(%)" }
            );
            if (data.value.pattern === 1) {
                getTiltTrendstabilityHistory({ equipmentCode: props.formData.equipmentCode, parentCode: data.value.code }).then((res) => {
                    if (res.code === 200) if (res.code === 200) tableData.value = res.data;
                });
            }
        } else {
            options.value = data.value.pointCodes.map((item, index) => ({ label: item.name, value: index, pointCodes: item.pointCodes }));
            selectValue.value = options.value[0].value;
            getstrainsensorbydatenowFn({ titleName: ["竖直方向", "水平方向"], yAxisName: "加速度（m/s^2）" });

            getstatisticsshocksensorbylocation({
                equipmentCode: props.formData.equipmentCode,
                locations: data.value.pointCodes[selectValue.value].pointCodes,
                monitoringObject: dataObj.order,
                parentCode: data.value.code,
                order: dataObj.order
            }).then((res) => {
                if (res.code === 200) tableData.value = res.data;
            });
            getshocksensormechanismvibration({
                equipmentCode: props.formData.equipmentCode,
                locations: data.value.pointCodes[selectValue.value].pointCodes,
                monitoringObject: dataObj.order,
                parentCode: data.value.code,
                order: dataObj.order
            }).then((res) => {
                if (res.code === 200) tableDatas.value = res.data;
            });
        }
    });
};
//年、季、月切换
const changeTime = (type) => {
    time.value = type;
    getstrainsensortendencyFn(
        { equipmentCode: props.formData.equipmentCode, statisticsType: type, monitorLocation: "主结构", parentCode: data.value.code },
        { titleName: "趋势水平", yAxisName: "趋势水平(%)" }
    );
};
const changes = (values) => {
    changeNumber.value = values;
    clearsInterval();
    if (values != 1) {
        getshocksensorFn({ titleName: ["竖直方向", "水平方向"], yAxisName: "加速度（m/s^2）" });
    } else {
        getstrainsensorbydatenowFn({ titleName: ["竖直方向", "水平方向"], yAxisName: "加速度（m/s^2）" });
    }
};
const close = () => {
    emits("close");
};
//下拉框切换
const change = () => {
    console.log(data.value);
    clearsInterval();
    changeNumber.value = 1;
    echarts.dispose(topRef.value);
    echarts.dispose(bottomRef.value);
    echarts.init(topRef.value);
    echarts.init(bottomRef.value);
    if (data.value.isStrain) {
        getstrainsensorbydatenowFn({
            titleName: ["实时数据"],
            yAxisName: selectValue.value === 1 ? options.value.find((item) => item.value === selectValue.value).label : `${options.value.find((item) => item.value === selectValue.value).label}(MPa)`
        });
        getstrainsensortendencybynowFn({ equipmentCode: props.formData.equipmentCode, parentCode: data.value.code });
        getstrainsensortendencyFn(
            { equipmentCode: props.formData.equipmentCode, statisticsType: time.value, monitorLocation: "主结构", parentCode: data.value.code },
            { titleName: "趋势水平", yAxisName: "趋势水平(%)" }
        );
    } else {
        getstrainsensorbydatenowFn({ titleName: ["竖直方向", "水平方向"], yAxisName: "加速度（m/s^2）" });
        getstatisticsshocksensorbylocation({
            equipmentCode: props.formData.equipmentCode,
            locations: data.value.pointCodes[selectValue.value].pointCodes,
            monitoringObject: data.value.order,
            parentCode: data.value.code,
            order: data.value.order
        }).then((res) => {
            if (res.code === 200) tableData.value = res.data;
        });
        getshocksensormechanismvibration({
            equipmentCode: props.formData.equipmentCode,
            locations: data.value.pointCodes[selectValue.value].pointCodes,
            monitoringObject: data.value.order,
            order: data.value.order,
            parentCode: data.value.code
        }).then((res) => {
            if (res.code === 200) tableDatas.value = res.data;
        });
    }
};
defineExpose({
    getData
});
</script>

<style lang="scss" scoped>
.one {
    color: #ff0000;
}
.two {
    color: #ffff00;
}
.three {
    color: #95cd21;
}
.nochange {
    font-size: 14px;
    color: #c5d8ff;
}
.change {
    color: #4ba6dd;
    font-size: 14px;
}
.histor-title {
    font-size: 14px;
    color: #c5d8ff;
}
.histor-text {
    font-size: 14px;
    padding-left: 8px;
}
.time {
    color: #4ba6dd;
}
.sensor {
    position: absolute;
    top: 32%;
    box-sizing: border-box;
    padding: 16px;
    left: 50%;
    transform: translate(-50%);
    width: 886px;
    height: 442px;
    background: rgba(27, 54, 70, 0.8);
    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 32px;
        .title {
            display: flex;
            align-items: center;
            color: #fff;
            .title-box {
                display: flex;
                justify-content: center;
                align-items: center;
                margin-right: 8px;
                width: 22px;
                height: 22px;
                border-radius: 50%;
            }
        }
        .select {
            display: flex;
            align-items: center;
            margin-right: 20px;
            color: #c5d8ff;
            .select-label {
                margin-right: 9px;
            }
            :deep(.el-input) {
                --el-input-border-color: #4ba6dd;
                --el-input-bg-color: #172b39;
            }
        }
    }
    .article {
        display: flex;
        align-items: center;
        width: 100%;
        .article-wrapper {
            position: relative;
        }
        .item {
            margin-top: 16px;
            width: calc(100% - 0px);
            height: 184px;
        }
        .table-main {
            box-sizing: border-box;
            width: 360px;
            text-align: center;
            color: #c5d8ff;
            table {
                width: 100%;
                height: 100%;
                border-collapse: collapse;
                thead {
                    background: rgba(75, 166, 221, 0.15);
                }

                th,
                tr {
                    height: 32px;
                    padding: 0;
                }
                tbody {
                    tr {
                        &:nth-of-type(even) {
                            background: rgba(75, 166, 221, 0.15);
                        }
                    }
                }
            }
        }
    }
    .choose {
        position: absolute;
        display: flex;
        align-items: center;
        color: #c5d8ff;
        margin-left: 10px;
        & > div:not(.point) {
            cursor: pointer;
        }
        .point {
            margin: 0 16px;
            width: 4px;
            height: 4px;
            background: #c5d8ff;
            border-radius: 50%;
        }
    }
    .header-choose {
        position: initial;
    }
    .choose-avtive {
        color: #4ba6dd;
    }
    .close {
        position: absolute;
        top: 19px;
        right: 15px;
        color: #c5d8ff;
        cursor: pointer;
    }
}
</style>
